package cn.pet.service.manage.auth;

import cn.pet.service.manage.context.GlobalContext;
import cn.pet.service.manage.entity.api.Result;
import cn.pet.service.manage.utils.JsonUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author ruoyi
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Resource
    private JWTUtil jwtUtil;

    /**
     * 退出处理
     * 
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        //todo:执行退出操作
        String token = request.getHeader("Authorization");
        try {
            if (token!=null && token.startsWith("Bearer")){
                token = token.substring("Bearer".length()+1);
                String userId = jwtUtil.getUserId(token);
                //删除
                GlobalContext.remove(Integer.parseInt(userId));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF8");
        response.setStatus(200);
        response.getWriter().print(JsonUtil.toJson(Result.ok("退出成功")));
    }
}
